package com.visionet.school.app.web.service.tclass;

import com.visionet.school.app.web.common.utils.PageUtils;
import com.visionet.school.app.web.entity.tclass.ClassNotice;
import com.visionet.school.app.web.entity.tclass.vo.ClassNoticeVo;
import com.visionet.school.app.web.repository.tclass.ClassNoticeRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by dzd on 2017/3/2.
 */

@Service
public class ClassNoticeService {

    private static final Logger logger = LoggerFactory.getLogger(ClassNoticeService.class);

    @Resource
    private ClassNoticeRepository classNoticeDao;

    public ClassNotice findClassById(String id){
        return classNoticeDao.findClassById(id);
    }

    public Map<String, Object> getNoticePage(final ClassNoticeVo classNoticeVo, String sortType){
        Pageable pageable = PageUtils.buildPageRequest(classNoticeVo.getPageInfo().getPageNumber(), classNoticeVo.getPageInfo().getPageSize(), sortType);
        Page<ClassNotice> objPage = classNoticeDao.findAll(new Specification<ClassNotice>() {
            public Predicate toPredicate(Root<ClassNotice> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> lstPredicates = new ArrayList<Predicate>();
//                if (StringUtils.isNotBlank(serArgs.get("serSbmc"))) {
//                    lstPredicates.add(cb.like(root.get("sbmc").as(String.class), "%" + serArgs.get("serSbmc") + "%"));
//                }


                if (StringUtils.isNotBlank(classNoticeVo.getClassId())) {
                    lstPredicates.add(cb.equal(root.get("classId"), classNoticeVo.getClassId()));
                }

                Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
                return cb.and(lstPredicates.toArray(arrayPredicates));
            }
        }, pageable);
        return PageUtils.getPageMap(objPage);
    }

    public void save(ClassNoticeVo classNoticeVo){
        ClassNotice classNotice = new ClassNotice();
        BeanUtils.copyProperties(classNoticeVo,classNotice);
        classNotice.setIsDeleted("0");
        classNoticeDao.save(classNotice);
    }
}
